# 通用服务器监控系统 Dockerfile
# 支持多阶段构建，优化镜像大小

# 构建阶段
FROM python:3.11-slim as builder

# 设置工作目录
WORKDIR /app

# 安装系统依赖
RUN apt-get update && apt-get install -y \
    gcc \
    g++ \
    && rm -rf /var/lib/apt/lists/*

# 复制依赖文件
COPY requirements.txt .

# 安装Python依赖到全局位置
RUN pip install --no-cache-dir -r requirements.txt

# 生产阶段
FROM python:3.11-slim

# 设置环境变量
ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1

# 创建非root用户
RUN groupadd -r monitor && useradd -r -g monitor monitor

# 设置工作目录
WORKDIR /app

# 从构建阶段复制Python包
COPY --from=builder /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages
COPY --from=builder /usr/local/bin /usr/local/bin

# 复制应用代码
COPY src/ ./src/
COPY config/ ./config/
COPY setup.py .
COPY README.md .
COPY requirements.txt .

# 创建必要的目录
RUN mkdir -p logs data && \
    chown -R monitor:monitor /app

# 安装应用
RUN pip install -e .

# 切换到非root用户
USER monitor

# 暴露端口（如果启用Web界面）
EXPOSE 8080

# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD python -c "import psutil; psutil.cpu_percent()" || exit 1

# 默认命令
CMD ["python", "-m", "monitor.server_monitor"]